const Book = require("../models/Book")
const db = require('../db')
const _ = require('lodash')
const { debug } = require('../utils/constant')

function exists(book) {
	const { title, author, publisher } = book
	const sql = `select * from book where title='${title}' and author='${author}' and publisher='${publisher}'`
	return db.queryOne(sql)
}

// 移除图书
async function removeBook(book) {
	if(book) {
		book.reset()
		if(book.fileName) {
			// 删除电子书信息的SQL语句
			const removeBookSql = `delete from book where fileName='${book.fileName}'`
			// 删除目录的SQL语句
			const removeContentsSql = `delete from contents where fileName='${book.fileName}'`
			await db.querySql(removeBookSql)
			await db.querySql(removeContentsSql)
		}
	}
}

async function insertContents(book) {
	const contents = book.getContents()
	console.log('contents', contents)
	if(contents && contents.length > 0) {
		for(let i = 0; i < contents.length; i++) {
			const content = contents[i]
			const _content = _.pick(content, [
				'fileName',
				'id',
				'href',
				'text',
				'order',
				'level',
				'label',
				'pid',
				'navId'
			])
			// console.log('_contents', _content)
			// 插入数据库
			await db.insert(_content, 'contents')
		}
	}
}

// 向数据库中添加图书
function insertBook(book) {
	return new Promise(async (resolve, reject) => {
		try {
			if(book instanceof Book) {	// book参数是否为Book对象的实例
				const result = await exists(book)
				if(result) {	// 图书以存在
					await removeBook(book)
					reject(new Error('电子书已存在'))
				} else {
					await db.insert(book.toDb(), 'book')
					await insertContents(book)
					resolve()
				}
			} else {
				reject(new Error('添加的图书对象不合法'))
			}
		} catch(e) {
			reject(e)
		}
	})
}

function updateBook(book) {
	return new Promise(async (resolve, reject) => {
		try {
			if (book instanceof Book) {
				// 获取book对象
				const result = await getBook(book.fileName)
				if(result) {
					const model = book.toDb()
					if(+result.updateType === 0) {
						reject(new Error('内置图书不能编辑'))
					} else {
						// console.log('model22', model)
						await db.update(model, 'book', `where fileName='${book.fileName}'`)
						resolve()
					}
				}
			} else {
				reject(new Error('添加的图书对象不合法'))
			}
		} catch(e) {
			reject(e)
		}
	})
}

function getBook(fileName) {
	return new Promise(async (resolve, reject) => {
		// 定义查询书本信息的sql语句
		const booksql = `select * from book where fileName='${fileName}'`
		// 定义查询书本目录的sql语句
		const contentsSql = `select * from contents where fileName='${fileName}' order by \`order\``
		const book = await db.queryOne(booksql)
		const contents = await db.querySql(contentsSql)
		// if(book) {
		// 	book.cover = Book.genCoverUrl(book)
		// }
		// 返回客户端数据
		console.log('booktest', book);
		if (book) {
			book.contentsTree = Book.genContentsTree(contents)
			resolve(book)
		} else { 
			reject(new Error('电子书不存在'))
		}
	})
	// return fileName
}

async function getCategory() {
	const sql = 'select * from category order by category asc'
	const result = await db.querySql(sql)

	const categoryList = []
	result.forEach(item => {
		categoryList.push({
			label: item.categoryText,
			value: item.category,
			num: item.num
		})
	})
	return categoryList
}

async function listBook(query) {
	debug && console.log(query)
	const {
		category,
		author,
		title,
		sort,
		page = 1,
		pageSize = 20
	} = query
	const offset = ( page - 1 ) * pageSize
	let bookSql = 'select * from book'
	let where = 'where'
	// 拼接标题的模糊查询语句
	title && (where = db.andLike(where, 'title', title))
	// 拼接作者的模糊查询语句
	author && (where = db.andLike(where, 'author', author))
	// 拼接分类的查询语句
	category && (where = db.and(where, 'categoryText', category))
	if( where !== 'where' ) {
		bookSql = `${bookSql} ${where}`
	}
	if (sort) {
		const symbol = sort[0]
		const column = sort.slice(1, sort.length)
		const order = symbol === '+' ? 'asc' : 'desc'
		// 拼接sql语句
		bookSql = `${bookSql} order by \`${column}\` ${order}`
	}
	// 定义分页查询
	let countSql = `select count(*) as count from book`
	if(where !== 'where') {
		countSql = `${countSql} ${where}`
	}
	const count = await db.querySql(countSql)
	console.log('count', count)
	bookSql = `${bookSql} limit ${pageSize} offset ${offset}`
	// 异步获取数据
	const list = await db.querySql(bookSql)
	// list.forEach(book => book.cover = book.genCoverUrl(book))
	// return new Promise((resolve, reject) => {
	// 	resolve()
	// })
	// async方法中返回的数据直接转换为promis对象
	return { list, count: count[0].count, page, pageSize }
}

function deleteBook(fileName) {
	return new Promise(async (resolve, reject) => {
		// 异步获取电子书
		let book = await getBook(fileName)
		if(book) {
			if(+book.updateType === 0) {
				reject(new Error('内置电子书不能删除'))
			} else {
				// 创建book对象
				const bookObj = new Book(null, book)
				const sql = `delete from book where fileName='${fileName}'`
				db.querySql(sql).then(() => {
					bookObj.reset()
					resolve()
				})
			}
		} else {
			reject(new Error('电子书不存在'))
		}
	})
}

module.exports = {
	insertBook,
	getBook,
	updateBook,
	getCategory,
	listBook,
	deleteBook
}